/**
 * ImageSearchUtil.java Create on 2012-7-31     
 *      
 * Copyright (c) 2012-7-31 by yiming     
 *      
 * @author <a href="alenzhangym@hotmail.com">Yiming</a>     
 * @version 1.0 
 */

package com.yimi.util;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.StatFs;
import android.view.View;
import android.widget.TextView;

import com.yimi.image.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

/**
 * TODO
 * 
 * @author Yiming
 * @version 1.0
 */
public class ImageSearchUtil {
    public static final int MAX_FILE_SIZE = 5237760; 
    public static final int MAX_SEND_SIZE = MAX_FILE_SIZE / 5;
    private static boolean sdcardAvailable;
    private static boolean sdcardAvailabilityDetected;
    public static final String sdcardFilePath = "/sdcard/searchimage/";
    public static final String previewFilePath = "/sdcard/previewimage/";
    public static final String romPreviewFilePath = "/data/data/com.yimi.image/files/download";
    public static final String romFilePath="/data/data/com.yimi.image/files/searchimage";
    public static boolean useSDCard;
  
    public static boolean createFile(String path, String fileName)
    {
            File filedir = new File(path);
            if (!filedir.exists())
                filedir.mkdirs();
            File file = new File(path + fileName);
            if (file.exists()) {
                file.delete();
            }
            try {
                file.createNewFile();
            } catch (IOException e) {
                return false;
            }
            return true;
    }
    
    public static void clearRomFileImage(){
        File filedir = new File(romFilePath);
        if(filedir.exists()){
            File[] files= filedir.listFiles();
            for(int i=0;i<files.length;i++){
                files[i].delete();
            }
        }
    }
    
    public static void clearPreviewmage(){
        File filePreDir = new File(romPreviewFilePath);
        if(filePreDir.exists()){
            File[] files= filePreDir.listFiles();
            for(int i=0;i<files.length;i++){
                files[i].delete();
            }
        }
    }
    
    public static boolean isPictureIsInFile(String path, final String fileName) {
        
        File file = new File(path + fileName);
        if (file.exists()) {
            return true;
        } else {
            return false;
        }
    }

    public static byte[] getPictureFromFile(String path, final String fileName) {
        byte[] buffer = null;
        File file = new File(path + fileName);
        if (file.exists()) {
            FileInputStream input = null;
            try {
                input = new FileInputStream(path + fileName);
                int lenth = input.available();
                buffer = new byte[lenth];
                input.read(buffer);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
        return buffer;
    }

    public static void savePictureToFile(final Bitmap b, final String fileName, final String path) {
        if (b == null)
            return;

        new Thread(new Runnable() {
            @Override
            public void run() {
                File file = new File(path + fileName);
                if (file.exists()) {
                    file.delete();
                    file = new File(path + fileName);
                }
                try {
                    FileOutputStream os = new FileOutputStream(path + fileName);
                    if (b.compress(Bitmap.CompressFormat.JPEG, 100, os)) {
                        os.flush();
                        os.close();
                    } else {
                        os.close();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * @param bitmap
     * @param path
     */
    public static void savePictureToFile(final byte[] bitmap, final String fileName,
            final String path) {
        final byte[] data = new byte[bitmap.length];
        System.arraycopy(bitmap, 0, data, 0, data.length);
        new Thread(new Runnable() {
            @Override
            public void run() {
                File file = new File(path + fileName);
                if (file.exists()) {
                    file.delete();
                    file = new File(path + fileName);
                }
                try {
                    FileOutputStream os = new FileOutputStream(path + fileName);
                    os.write(data);
                    os.flush();
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * @return SD is available ?
     */
    public static synchronized boolean detectSDCardAvailability() {
        boolean result = false;
        try {
            Date now = new Date();
            long times = now.getTime();
            String fileName = "/sdcard/" + times + ".test";
            File file = new File(fileName);
            result = file.createNewFile();
            file.delete();
        } catch (Exception e) {
            // Can't create file, SD Card is not available
            e.printStackTrace();
        } finally {
            sdcardAvailabilityDetected = true;
            sdcardAvailable = result;
        }
        return result;
    }

    /**
     * @return SD is available ?
     */
    public static boolean isSDCardAvailable() {
        if (!sdcardAvailabilityDetected) {
            sdcardAvailable = detectSDCardAvailability();
            if (getSDCardSize() > MAX_FILE_SIZE)
            {
                sdcardAvailabilityDetected = true;
            }
        }
        return sdcardAvailable;
    }

    public static boolean isRomAvailable() {
        boolean romenable = false;
        if (getRomSize() > MAX_FILE_SIZE) {
            romenable = true;
        }
        return romenable;
    }

    public static long getRomSize() {
        long size = 0;
        File rootDir = Environment.getRootDirectory();
        if (rootDir != null) {
            StatFs statFs = new StatFs(rootDir.getPath());
            long blockSize = statFs.getBlockSize();
            long availableBlocks = statFs.getBlockCount();
            size = availableBlocks * blockSize;
        }
        return size;
    }

    public static long getSDCardSize() {
        long size = 0;
        File sdcardDir = Environment.getExternalStorageDirectory();
        if (sdcardDir != null) {
            StatFs statFs = new StatFs(sdcardDir.getPath());
            long blockSize = statFs.getBlockSize();
            long availableBlocks = statFs.getBlockCount();
            size = availableBlocks * blockSize;
        }
        return size;
    }

    public static Dialog dialogShow(Dialog dialog, Activity activity, String msg) {
        View view;
        TextView text;

        if (dialog != null && dialog.isShowing()) {
            return dialog;
        }
        view = View.inflate(activity, R.layout.loading_diloag, null);
        dialog = new Dialog(activity, R.style.LoadingDialog);
        dialog.setContentView(view);
        text = (TextView) view.findViewById(R.id.textview);
        text.setText(msg);
        return dialog;
    }
}
